package com.caosy.grassthinkremote.service;

import cn.hutool.core.collection.CollUtil;
import com.caosy.grassthinkremote.common.GtrConstant;
import com.caosy.grassthinkremote.common.RespData;
import com.caosy.grassthinkremote.entity.Commodity;
import com.caosy.grassthinkremote.entity.vo.CommodityReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommodityService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加商品
     * @param req
     * @return
     */
    public RespData add(CommodityReq req) {
        //先去redis中查询商品列表
        List<Commodity> commodityList = (List<Commodity>) redisTemplate.opsForValue().get(GtrConstant.REDIS_QUERY_COMMODITY_LIST_KEY);
        //是否为空
        Long addId = 1L;
        if (CollUtil.isEmpty(commodityList)) {
            //为空创建一个新的
            commodityList = CollUtil.newArrayList();
        } else {
            //计算要插入的商品的id
            List<Long> ids = commodityList.stream().map(Commodity::getId).collect(Collectors.toList());
            Long existMaxId = CollUtil.max(ids);
            addId = existMaxId + 1;
        }

        //req转换为commodity实体
        Commodity commodity = req.toCommodity();
        commodity.setId(addId);
        //插入集合，放到redis
        commodityList.add(commodity);

        redisTemplate.opsForValue().set(GtrConstant.REDIS_QUERY_COMMODITY_LIST_KEY,commodityList);

        return RespData.getSuccess("添加商品成功！");
    }
}
